import { deepCopy } from '@/utils/common'
import { fetchSongInfo } from './api'

export default {
  namespaced: true,
  state: () => ({
    list: [],
    total: 0,
    play: {},
    playIndex: 0
  }),
  getters: {
    player (state) {
      return state.play
    },
    total (state) {
      return state.total
    },
    isFirst (state) {
      return state.playIndex === 0
    },
    isEnd (state) {
      return state.playIndex === state.list.length - 1
    }
  },
  actions: {
    async skip ({ commit, state }, index) {
      commit('SET_INDEX', index)
      const { song_id } = state.list[index]
      const { data } = await fetchSongInfo(song_id)
      commit('SET_PLAY', data)
    },
    async next ({ dispatch, state }) {
      if (state.isEnd) {
        return
      }
      dispatch('skip', state.playIndex + 1)
    },
    async prev ({ dispatch, state }) {
      if (state.isFirst) {
        return
      }
      dispatch('skip', state.playIndex - 1)
    },
    replaceSongList ({ commit, dispatch }, songs) {
      commit('SET_SONGS', songs)
      dispatch('skip', 0)
    },
    insertSong ({ commit, state, dispatch }, song) {
      const songs = deepCopy(state.list)
      songs.splice(state.playIndex + 1, 0, song)
      commit('SET_SONGS', songs)
      const index = songs.findIndex(({ id }) => id === song.id)
      dispatch('skip', index)
    },
    appendSong ({ commit }, song) {
      commit('APPEND_SONGS', song)
    }
  },
  mutations: {
    SET_PLAY (state, payload) {
      state.play = payload.data
    },
    SET_SONGS (state, payload) {
      state.list = payload
    },
    APPEND_SONGS (state, payload) {
      state.list.push(payload)
    },
    SET_INDEX (state, payload) {
      state.playIndex = payload
    }
  }
}